package com.liangzhong.global
{
	import com.common.stdlib.ArrayUtil;
	import com.liangzhong.model.AppData;
	
	import flash.utils.*;
	
	/**
	 * 消息头
	 * @author lxh
	 * 
	 */	
	public class CMD_Head
	{
		/**
		 *数据长度 
		 */		
		public static const Size :uint = 2 + 2 + 2 + 4;
		
		/**
		 *消息总长度，即（消息头+消息体）总长度 
		 */		
		public var dataLen    :uint;
		/**
		 *服务器类型 
		 */		
		public var serverType :uint;
		/**
		 *方法ID，表示应用服务器中方法序号 
		 */		
		public var methodId   :uint;
		/**
		 * 
		 */		
		public var userID     :uint;
		
		public function CMD_Head()
		{
		}
		
		/**
		 *读取字节数据 
		 * @param data
		 * @return 
		 * 
		 */		
		public static function readData(data:ByteArray):CMD_Head
		{
			var result:CMD_Head=new CMD_Head;
			if(data.bytesAvailable < 10)
			{
				trace("head length less than 10!");
				return result;
			}
			try
			{
				result.dataLen    = data.readUnsignedShort();
				result.serverType = data.readUnsignedShort();
				result.methodId   = data.readUnsignedShort();
				result.userID     = data.readUnsignedInt();
			}
			catch(e :Error)
			{
				trace(e.toString());
			}
			
			return result;
		}
		/**
		 *写入字节数据 
		 * @return 
		 * 
		 */		
		public function toByteArray():ByteArray
		{
			var result:ByteArray = ArrayUtil.newLitteEndianByteArray();
			
			result.writeShort(dataLen);
			result.writeShort(serverType);
			result.writeShort(methodId);
			result.writeUnsignedInt(userID);
			result.position = 0;
			return result;
		}
		/**
		 *设置包头数据 
		 * @param len
		 * @param sType
		 * @param mtid
		 * @param uid
		 * 
		 */		
		public function setData(len:int,
								sType:int,
								mtid :int,
								uid :int):void
		{
			dataLen    = len;
			serverType = sType;
			methodId   = mtid;
			userID     = uid;
		}
		/**
		 *获取一个已经写入Head 数据 的byteArray 
		 * @param len
		 * @param sType
		 * @param mtid
		 * @param uid
		 * @return 
		 * 
		 */		
		public static function getHeadByteArrayBuff(len:int,
													sType:int,
													mtid :int,
													uid :int = 0):ByteArray
		{
			var sendBuf :ByteArray = ArrayUtil.newLitteEndianByteArray();
			var cmd_Head :CMD_Head = new CMD_Head();
			if(uid == 0)
			{
				uid = AppData.getInstance().user.uid;
			}
			cmd_Head.setData(len ,sType,mtid,uid);
			sendBuf.writeBytes(cmd_Head.toByteArray(),0,cmd_Head.getSize());
			return sendBuf;
		}
		/**
		 *获取大小 
		 * @return 
		 */		
		public function getSize():uint
		{
			return Size;
		}
	}
}